<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class Alibabadata
{
	private $urlApi = "http://gw.open.1688.com/openapi/param2/1/";
	public function __construct()
	{
		$this->CI =& get_instance();
		$this->db = $this->CI->load->database('default', TRUE);
		$this->CI->load->library('amazondata');
		$this->CI->load->model('Function_m','fun');
		$this->CI->load->model('Purchase_m','purchase');
	}
	/**
	 * 获取订单物流信息 物流单号
	 * @param $appKey 开发者账号appkey
	 * @param $appScret 密钥
	 */
	public function getAlibabaLogisticsList(){
		$appKey = "9515253";
		$appScret = "0lLOe8Nfd1mm";
		$sql = "SELECT * FROM db_purchase_list WHERE made_factory = 3 AND  made_way = 2  "; // made_way 外采购  1688
		$rs  = $this->db->query($sql)->result_array();
		if(count($rs)>0){
			foreach($rs as $key=>$value){

				//$orderId = "136969871392485348";   //211853-3XL 商品采购物流测试  133012043023485348 已发货
				$orderId = $value['tb_ordersn'];
				//获取签名 com.alibaba.logistics:alibaba.trade.getLogisticsTraceInfo.buyerView
				$api_relative_path = 'param2/1/com.alibaba.logistics/alibaba.trade.getLogisticsInfos.buyerView' . '/' . $appKey;
				$arr_param = array('webSite' =>1688, 'orderId' =>$orderId);
				$sign = $this->getApiSign($api_relative_path,$appScret, $arr_param);
				//获取api签名结束

				//根据签名获取订单数据
				$request_url = $this->urlApi . "com.alibaba.logistics/alibaba.trade.getLogisticsInfos.buyerView/" .$appKey;
				$data = 'webSite=1688&orderId='.$orderId. '&_aop_signature=' . $sign;
				$result = $this->sendCurlPostRequest($request_url, $data);
				echo $orderId;
				echo "<br/>";
				//print_r($result);exit;
				if(isset($result['errorCode'])&&$result['errorCode']=="success"){
					//此处没有返回相关运单号
					//$this->db->update("db_purchase_list",array("made_way"=>3)," id = '".$value['id']."'");
				}else{
					if(isset($result['result'])&&$result['result'][0]['logisticsId']){
						$arr_data = array();
						$arr_data['tborder'] = $value['tb_ordersn'];
						$arr_data['kdname'] = $result['result'][0]['logisticsCompanyName'];
						$arr_data['kdnumber'] = $result['result'][0]['logisticsBillNo'];
						//$logisticsId = $result['result'][0]['logisticsId'];
						//print_r($logisticsId);exit;
						$serialize_data = $arr_data['kdnumber'];
						//$serialize_data = serialize($arr_data);  status = 2 采购完成 ps = 2 已支付
						$this->db->update("db_purchase_list",array("tb_kd"=>$serialize_data,'kdname'=>$arr_data['kdname'],'status'=>2,"made_way"=>3,'ps'=>2)," id = '".$value['id']."'");

						$auto = "auto";
						$sqls  =" insert into db_purchase_status set s_sid = '".$value['id']."',s_zt ='24',s_zt_content='采购完成',s_updatetime='".date("Y-m-d H:i:s")."', s_admins = '".$auto."'";
						$this->db->query($sqls);
						//$this->CI->purchase->upstatus_list($value['id'],24,'采购完成');
						//添加日志信息
						$sql = "SELECT * FROM db_purchase_list WHERE id  = '{$value['id']}' ";
						$detail  = $this->db->query($sql)->row_array();

						$msg = "状态由：已支付,更改为：采购完成,运单号".$arr_data['kdnumber'].",快递公司:".$arr_data['kdname'].",订单号：".$value['tb_ordersn'];
						$arr_logs['createtime'] = date("Y-m-d H:i:s");
						$arr_logs['goods_code'] = $detail['orderstockid'];
						$arr_logs['details'] = $msg;
						$arr_logs['username'] = "auto";
						$arr_logs['userid'] = 0;
						$arr_logs['purchase_id'] = $value['id'];
						$this->db->insert('db_externalbuy_log', $arr_logs);




					}
				}

			}

		}


	}
	//获取api数字签名
	protected function getApiSign($api_relative_path,$appSecret,$arr_param){
		$apiInfo = $api_relative_path;//此处请用具体api进行替换
		//配置参数，请用apiInfo对应的api参数进行替换
		$code_arr = $arr_param;
		$aliParams = array();
		foreach ($code_arr as $key => $val) {
			$aliParams[] = $key . $val;
		}
		sort($aliParams);
		$sign_str = join('',$aliParams);
		$sign_str = $apiInfo.$sign_str;
		$code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
		return $code_sign;
	}
	/*
	* 通过refreshToken换取accessToken
	*/
	protected function getAccessToken($refreshtoken,$appkey,$appsecret)
	{
		$getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/getToken/'.$appkey;
		//此处不需要签名  注：此接口必须使用POST方法提交；必须使用https
		$data = 'grant_type=refresh_token&client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken;
		$result = $this->sendCurlPostRequest($getTokenUrl,$data);
		return $result;
	}
	/*
	* 半年期限，剩余30天之内可以使用postponeToken接口换取新的refresh_token
	 * 若调用该接口则之前使用refresh_token失效，新获取的refresh_token生效
	*/
	protected function getRefreshToken($refreshtoken,$access_token,$appkey,$appsecret)
	{
		$getTokenUrl = 'https://gw.api.alibaba.com/openapi/param2/1/system.oauth2/postponeToken/'.$appkey;
		//此处不需要签名  注：此接口可以使用Get或POST方法提交；必须使用https
		$data = 'client_id='.$appkey.'&client_secret='.$appsecret.'&refresh_token='.$refreshtoken.'&access_token='.$access_token;
		$result = $this->sendCurlPostRequest($getTokenUrl,$data);
		//返回数组类型的数据格式
		// {"aliId":"8888888888","resource_owner":"xxx","memberId":"xxxxxxx","expires_in":"36000","refresh_token":"479f9564-1049-456e-ab62-29d3e82277d9","access_token":"f14da3b8-b0b1-4f73-a5de-9bed637e0188","refresh_token_timeout":"20121222222222+0800"}
		return $result;
	}
	/*
	 * 发送请求
	 * @param  $url
	 * @param $post_data
	 */
	protected function sendCurlPostRequest($url,$post_data)
	{
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		// https请求 不验证证书和hosts
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		//post请求方式
		curl_setopt($ch,CURLOPT_POST,TRUE);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
		curl_setopt($ch,CURLOPT_TIMEOUT,300);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$response = curl_exec($ch);
		curl_close($ch);
		$response = json_decode($response,TRUE);
		return $response;
	}

}